class CustomPromise {
  #state = "pending";
  #result = null;
  #TaskQueues = [];

  constructor(excutor) {
    const resolve = (data) => {
      if (this.#state !== "pending") return;
      console.log("9--resolve", data);
      this.#state = "fulfilled";
      this.#result = data;
      this.#run();
    };

    const reject = (reason) => {
      if (this.#state !== "pending") return;
      console.log("reject", reason);
      this.#state = "rejected";
      this.#result = reason;
      this.#run();
    };
    try {
      excutor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  #handleCallback(callback, resolve, reject) {
    if (typeof callback !== "function") {
      // 状态穿透,放到微队列执行
      queueMicrotask(() => {
        const settled = this.#state === "fulfilled" ? resolve : reject;
        settled(this.#result);
      });
      return;
    }
    queueMicrotask(() => {
      try {
        const data = callback(this.#result);
        resolve(data);
      } catch (error) {
        reject(error);
      }
    });
  }

  #run() {
    // console.log("run", this.#TaskQueues);
    if (this.#state === "pending") return;

    while (this.#TaskQueues.length) {
      const { onFulfilled, onRejected, resolve, reject } =
        this.#TaskQueues.shift();
      if (this.#state === "fulfilled") {
        // 执行onFulfilled
        this.#handleCallback(onFulfilled, resolve, reject);
      } else {
        // 执行onRejected
        this.#handleCallback(onRejected, resolve, reject);
      }
    }
  }
  then(onFulfilled, onRejected) {
    // console.log("then方法");
    // 返回一个新的Promise对象
    return new CustomPromise((resolve, reject) => {
      this.#TaskQueues.push({
        onFulfilled,
        onRejected,
        resolve,
        reject,
      });

      // 尝试执行队列中的任务
      this.#run();
    });
  }
  catch(err) {
    console.log("catch方法", err);
    return this.then(null, err);
  }
}

const p = new CustomPromise((resolve, reject) => {
  resolve("1");
  //   reject("fail");
});

console.log("84", p);
const p1 = p
  .then(
    (res) => {
      console.log("87:", res);
      return res + "2";
    },
    (err) => {
      console.error("88:", err);
    }
  )
  .then((res) => {
    console.log("90:", res);
  })
  .catch((err) => {
    console.error("89:", err);
  });
